﻿<%@ WebHandler Language="C#" Class="ContainerInstoreVue3PageHandler" %>

/* Description:入库申请
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan 
 * create Date:2024.8.15
 */

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using BusinessRule.DTO;
using DatabaseAccess.DBUtility;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Net;
using BusinessRule.Common;
using System.Linq;
using System.Configuration;

public class ContainerInstoreVue3PageHandler : IHttpHandler
{
    uLMSCommonIBusiness m_Common = uMESBusinessFactory.instance.GetuLMSCommonObject();
    uLMSContainerInStoreIBusiness m_ContainerData = uMESBusinessFactory.instance.GetuLMSContainerInStoreObject();
    string ToAppID_WMS = ConfigurationManager.AppSettings["ToAppID_WMS"];
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (System.IO.StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                uMESProcessResult r = new uMESProcessResult();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getERPInStoreLocationList":
                        r = getERPInStoreLocationList(jObject);//获取ERP库存位置
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "saveData":
                        r = saveData(jObject, context);//保存入库信息
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                uMESProcessResult r = new uMESProcessResult() { ReturnData = null, RowCount = "0", Code = "500", Message = e.Message };
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    //获取ERP库存位置
    uMESProcessResult getERPInStoreLocationList(JObject obj)
    {
        DataTable dt = m_ContainerData.GetInventoryLocation();
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        return new uMESProcessResult() { ReturnData = dt, RowCount = dt.Rows.Count.ToString(), Code = "200", Message = "请求成功" };
    }

    //保存入库信息
    uMESProcessResult saveData(JObject obj, HttpContext context)
    {
        CurrentUserInfo m_UserInfo = m_Common.GetUserInfo(obj["employeename"].ToString(), "");
        DataTable dtContainer = JsonConvert.DeserializeObject<DataTable>(obj["containerList"].ToString());
        Dictionary<string, object> para = new Dictionary<string, object>();

        Dictionary<string, string> hasFirstIdentifyProductPara = new Dictionary<string, string>();
        hasFirstIdentifyProductPara.Add("PRODUCTNAME", dtContainer.Rows[0]["productname"].ToString()); //物料编号
        hasFirstIdentifyProductPara.Add("FACTORYID", m_UserInfo.FactoryID.ToString()); //add by longb 用于查询分厂控制点解除处理人员
        string msg = "";
        // 查询是否存在未解除的首件鉴定
        if (m_ContainerData.CheckFirstIdentifyProduct(hasFirstIdentifyProductPara, ref msg))
        {
            return new uMESProcessResult() { ReturnData = false, RowCount = "0", Code = "200", Message = "当前件号存在未解除的首件鉴定或质量评审，不能入库" };
        }

        if (CheckSpecUnqualifiedReason(dtContainer)) // 判断批次工序是否存在报修数>0 没有维护不合格原因 add by longb 2023-12-26
        {
            return new uMESProcessResult() { ReturnData = false, RowCount = "0", Code = "200", Message = "请联系工艺员补全不合格原因再办理入库" };
        }

        foreach (DataRow dr in dtContainer.Rows)
        {
            para = new Dictionary<string, object>();
            // 判断是否应该军检 add:Wangjh
            para.Add("IsArmyCheck", 0);
            string strSql = @"
select * from ArmyCheckDirInfo ad 
where ad.partName='{0}' and ad.processno=(select process_no from workflow where workflowid='{1}') and ad.ArmyYear={2} and ad.isuse=0";
            string sql = string.Format(strSql, dr["productname"].ToString(), dr["workflowid"].ToString(), DateTime.Now.Year);
            DataTable armyDt = DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(sql);
            if (armyDt.Rows.Count > 0 && armyDt.Rows[0]["armyCheckType"].ToString() == "成品军检")
            {
                para["IsArmyCheck"] = 1;
            }
            para.Add("ZPCTC", dr["qty"].ToString());//批次投产数量
            para.Add("ProductOrderNo", dr["mfgordername"].ToString());//生产订单号
            para.Add("PartName", dr["productdesc"].ToString());//零件名称
            para.Add("PartNo", dr["productname"].ToString());//物料编号
            para.Add("UnqualifiedApproveNo", dr["zbhgdh"].ToString());//不合格品审理单号
            para.Add("EmployeeId", m_UserInfo.EmployeeID);
            para.Add("WorkflowID", dr["workflowid"].ToString());
            para.Add("Detaildt", new DataTable());//入库机型去向信息
            para.Add("Batch", dr["containername"].ToString());//流水卡号
            para.Add("ContainerID", dr["containerid"].ToString());
            para.Add("StoreInType", dr["instoreType"].ToString() == "副产品入库" ? "F" : "");//入库类型
            para.Add("BranchFactory", dr["originalFactorycode"].ToString());//生产分厂
            para.Add("EntrustUnit", dr["entrustFactorycode"].ToString());//委托单位
            para.Add("LGORT", dr["stockLocation"].ToString());//库存位置
            para.Add("ReplaceMaterialNumber", dr["replaceMaterialNumber"].ToString());//代料单号
            para.Add("MachineType", dr["productfamily"].ToString());//机型
            para.Add("ZLPNUM", dr["zlpNum"].ToString());//炉批顺序号
            para.Add("Notes", dr["notes"].ToString());//备注

            para.Add("LossNum", dr["lossqty"].ToString());//报废数（单价单卡时固定为0）
            para.Add("SubmitNum", dr["submitqty"].ToString());//提交数（单价单卡时固定为1）
            para.Add("QualifiedNum", dr["passqty"].ToString());//合格数（单价单卡时固定为1）
            para.Add("OnceQualifiedNum", dr["onceQualifiedNum"].ToString());//一次交检合格数（单价单卡时固定为1）
            para.Add("QualityPolicyNumber", dr["qualityPolicyNumber"].ToString());//质保单数
            para.Add("OilSealDate", dr["oilSealDate"].ToString());//油封日期 add zhunan 2025.9.11

            para.Add("oilPeriod", dr["oilPeriod"].ToString());//油封周期
            para.Add("allsetMsg", dr["allsetMsg"].ToString());//配套发送信息
            para.Add("allsetProductname", dr["allsetProductname"].ToString());//配套零件号
            para.Add("allsetContainername", dr["allsetContainername"].ToString());//配套批次号

            para.Add("Type", "");
            para.Add("FactoryTryLatheNum", "");
            para.Add("AppendTryLatheNum", "");
            para.Add("TestTryLatheNum", "");
            para.Add("SubmitTryLatheNum", "");
            para.Add("InFactoryWorkTime", "");
            para.Add("FactoryTryLatheTime", "");
            para.Add("AppendTryLatheTime", "");
            para.Add("TestTryLatheTime", "");
            para.Add("LathePlatform", "");
            para.Add("ProblemDesc", "");
            para.Add("employeeid", m_UserInfo.EmployeeID);//当前登录人id

            m_ContainerData.InsertContainerInStoreData(para);

            saveToTable(para);
            //add:Wangjh 写入数据库
            LogHelp.WriteOrcale("入库日志记录" + "@^" + "批次" + para["Batch"] + "@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_UserInfo.FullName);
        }

        if (para["IsArmyCheck"].ToString() == "1")
        {
            msg = "当前件号需要成品军检、请先到QMS完成相应审批流才能正常ERP入库";
        }
        else
        {
            msg = "入库成功";
        }
        return new uMESProcessResult() { ReturnData = true, RowCount = "0", Code = "200", Message = msg };
    }

    //判断批次工序是否存在报修数>0 没有维护不合格原因
    bool CheckSpecUnqualifiedReason(DataTable dtContainer)
    {
        string containerid = "";
        foreach (DataRow dr in dtContainer.Rows)
        {
            containerid += dr["ContainerID"].ToString() + ",";
        }
        string selectStr = @"
select * from containercheckinfo c 
where c.reworkqty>0 and unqualifiedfeatureids is not null 
and c.unqualifiedreasoncode is null and c.containerid in ('" + containerid.TrimEnd(',').Replace(",", "','") + "')";
        DataTable dt = DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(selectStr);
        return dt.Rows.Count > 0;
    }

    void saveToTable(Dictionary<string, object> dic)
    {
        Dictionary<string, object> para = new Dictionary<string, object>();
        para["warehouseCode"] = "WH301";//仓库代码【必填字段】
        para["companyCode"] = "LYDL";//货主代码【必填字段】
        para["bizDataType"] = dic["StoreInType"].ToString() == "F" ? "2" : "1";//1-正常入库、2-副产品入库【必填字段】
        para["bizDataNo"] = dic["ProductOrderNo"].ToString();//生产订单号【必填字段】
        para["docNo"] = "";//业务流水号(订单集成时MES从ERP获取,目前置空)【必填字段】
        para["supplierCode"] = dic["BranchFactory"].ToString();//供应商ID，取MES分厂代码【必填字段】
        //para["storageLocation"] = dic["LGORT"].ToString();//库存地点【必填字段】

        para["ZWTDW"] = dic["EntrustUnit"].ToString();//委托单位
        para["ZLPNUM"] = dic["ZLPNUM"].ToString();//炉批顺序号
        para["ZPCTC"] = dic["ZPCTC"].ToString();//批次投产数
        para["QMS_Passqty"] = "";//军检-合格数
        para["QMS_RepairQty"] = "";//军检-返修数
        para["QMS_LossQty"] = "";//军检-报废数
        para["QMS_Customer"] = "";//军检-顾客代表
        para["QMS_CusAuditDate"] = "";//军检-顾客代表审核时间

        //预留字段1~10
        para["userDef01"] = "";
        para["userDef02"] = "";
        para["userDef03"] = "";
        para["userDef04"] = "";
        para["userDef05"] = "";
        para["userDef06"] = "";
        para["userDef07"] = "";
        para["userDef08"] = "";
        para["userDef09"] = "";
        para["userDef10"] = "";

        DataTable dt = new DataTable();
        dt.Columns.Add("lineNo", typeof(int));//业务流水行项目号【必填字段】
        dt.Columns.Add("itemCode", typeof(string));//物料编码【必填字段】
        dt.Columns.Add("itemName", typeof(string));//物料名称（描述）【必填字段】
        dt.Columns.Add("modelSpecs", typeof(string));//规格型号
        dt.Columns.Add("unit", typeof(string));//计量单位
        dt.Columns.Add("qty", typeof(int));//入库数量

        dt.Columns.Add("TJMNG", typeof(int));//提交数量【必填字段】
        dt.Columns.Add("ZHGSL", typeof(int));//合格数量【必填字段】
        dt.Columns.Add("BFSL", typeof(int));//报废数量
        dt.Columns.Add("ZYCHGSL", typeof(int));//一次交检合格数
        dt.Columns.Add("ZZBDSL", typeof(int));//质保单数量

        dt.Columns.Add("ZDLDH", typeof(string));//代料单号
        dt.Columns.Add("ZBHGDH", typeof(string));//不合格品审理单号

        dt.Columns.Add("batchNum", typeof(string));//生产批次【必填字段】
        dt.Columns.Add("serialCode", typeof(string));//序列号
        dt.Columns.Add("suitableModel", typeof(string));//适用机型
        dt.Columns.Add("inspStatus", typeof(string));//军检状态
        dt.Columns.Add("revisionLevel", typeof(string));//设计版次【必填字段】
        dt.Columns.Add("mdfDate", typeof(string));//生产日期【必填字段】
        dt.Columns.Add("preservationDate", typeof(string));//油封日期
        dt.Columns.Add("accompanyingDocs", typeof(string));//随带文件
        dt.Columns.Add("coCNumber", typeof(string));//合格证编号
        dt.Columns.Add("specialInv", typeof(string));//特殊库存
        dt.Columns.Add("invType", typeof(string));//库存类型
        dt.Columns.Add("restrictions", typeof(string));//限制信息
        dt.Columns.Add("msfNumber", typeof(string));//代料单号
        dt.Columns.Add("ncrNo", typeof(string));//不合格品审理单
        dt.Columns.Add("applicableScope", typeof(string));//使用范围
        dt.Columns.Add("remarks", typeof(string));//备注
        dt.Columns.Add("allsetMsg", typeof(string));//配套发送信息
        dt.Columns.Add("containerInfoItemList", typeof(DataTable));//成套发放明细
        dt.Columns.Add("storageLocation", typeof(string));//库存地点

        //预留字段
        dt.Columns.Add("userDef01", typeof(string));
        dt.Columns.Add("userDef02", typeof(string));
        dt.Columns.Add("userDef03", typeof(string));
        dt.Columns.Add("userDef04", typeof(string));
        dt.Columns.Add("userDef05", typeof(string));
        dt.Columns.Add("userDef06", typeof(string));
        dt.Columns.Add("userDef07", typeof(string));
        dt.Columns.Add("userDef08", typeof(string));
        dt.Columns.Add("userDef09", typeof(string));
        dt.Columns.Add("userDef10", typeof(string));

        DataRow dr = dt.NewRow();
        dr["lineNo"] = 1;//业务流水行项目号【必填字段】
        dr["itemCode"] = dic["PartNo"].ToString();//物料编码【必填字段】
        dr["itemName"] = dic["PartName"].ToString();//物料名称【必填字段】

        string query = @"
SELECT cci.containername,cci.togetherflag,cci.containerno,cci.productname,cci.productdescription,cci.productrevision,cci.productid,p.MaterialSpecification,
       u.uomname,wf.part_revid,to_char(cci.originalstartdate,'yyyy-mm-dd') originalstartdate,mfg.lgort
FROM containercurrentinfo cci
LEFT JOIN product p ON p.productid = cci.productid
LEFT JOIN container c ON c.containerid = cci.containerid
LEFT JOIN uom u ON u.uomid = c.uomid
LEFT JOIN workflow wf ON wf.workflowid = p.workflowid
LEFT JOIN mfgorder mfg ON mfg.mfgorderid = cci.mfgorderid
WHERE cci.containername = '{0}'";
        query = string.Format(query, dic["Batch"].ToString());

        DataTable dtProductInfo = DatabaseHelper.Query_ReturnDatTable(query);
        if (dtProductInfo.Rows.Count > 0)
        {
            dr["modelSpecs"] = dtProductInfo.Rows[0]["MaterialSpecification"].ToString();//规格型号
            dr["unit"] = dtProductInfo.Rows[0]["uomname"].ToString();//计量单位
            dr["storageLocation"] = dtProductInfo.Rows[0]["lgort"].ToString();//库存地点
        }
        else
        {
            dr["modelSpecs"] = "";
            dr["unit"] = "";
            dr["storageLocation"] = "";
        }

        dr["qty"] = Convert.ToInt32(dic["ZPCTC"]);//入库数量
        dr["TJMNG"] = Convert.ToInt32(dic["SubmitNum"]);//提交数量【必填字段】
        dr["ZHGSL"] = Convert.ToInt32(dic["QualifiedNum"]);//合格数量【必填字段】
        dr["BFSL"] = Convert.ToInt32(dic["LossNum"]);//报废数量
        dr["ZYCHGSL"] = Convert.ToInt32(dic["OnceQualifiedNum"]);//一次交检合格数
        dr["ZZBDSL"] = Convert.ToInt32(dic["QualityPolicyNumber"]);//质保单数量
        dr["ZDLDH"] = dic["ReplaceMaterialNumber"].ToString();//代料单号
        dr["ZBHGDH"] = dic["UnqualifiedApproveNo"].ToString();//不合格品审理单号

        dr["batchNum"] = dtProductInfo.Rows.Count > 0 ? dtProductInfo.Rows[0]["togetherflag"].ToString() : "";//生产批次【必填字段】
        dr["serialCode"] = dtProductInfo.Rows.Count > 0 ? dtProductInfo.Rows[0]["containername"].ToString() : "";//序列号(流水卡号)
        dr["suitableModel"] = dic["MachineType"].ToString();//适用机型
        dr["inspStatus"] = "";//军检状态
        dr["revisionLevel"] = dtProductInfo.Rows.Count > 0 ? dtProductInfo.Rows[0]["part_revid"].ToString() : "";//设计版次【必填字段】
        dr["mdfDate"] = dtProductInfo.Rows.Count > 0 ? dtProductInfo.Rows[0]["originalstartdate"].ToString() : "";//生产日期【必填字段】
        dr["preservationDate"] = dic["OilSealDate"].ToString();//油封日期
        dr["accompanyingDocs"] = "";//随带文件
        dr["coCNumber"] = "";//合格证编号
        dr["specialInv"] = "";//特殊库存
        dr["invType"] = "";//库存类型
        dr["restrictions"] = "";//限制信息
        dr["msfNumber"] = dic["ReplaceMaterialNumber"].ToString();//代料单号
        dr["ncrNo"] = dic["UnqualifiedApproveNo"].ToString();//不合格品审理单
        dr["applicableScope"] = "";//使用范围
        dr["remarks"] = dic["Notes"].ToString();//备注
        dr["allsetMsg"] = dic["allsetMsg"].ToString();//配套发送信息


        DataTable dtContainerInfoItemList = new DataTable();
        dtContainerInfoItemList.Columns.Add("itemCode", typeof(string));//配套零件号
        dtContainerInfoItemList.Columns.Add("batchNum", typeof(string));//配套批次号

        DataRow r = dtContainerInfoItemList.NewRow();
        r["itemCode"] = dic["allsetProductname"].ToString();
        r["batchNum"] = dic["allsetContainername"].ToString();
        dtContainerInfoItemList.Rows.Add(r);

        dr["containerInfoItemList"] = dtContainerInfoItemList;//成套发放明细

        dr["userDef01"] = dic["oilPeriod"].ToString();
        dr["userDef02"] = "";
        dr["userDef03"] = "";
        dr["userDef04"] = "";
        dr["userDef05"] = "";
        dr["userDef06"] = "";
        dr["userDef07"] = "";
        dr["userDef08"] = "";
        dr["userDef09"] = "";
        dr["userDef10"] = "";

        dt.Rows.Add(dr);

        para["itemList"] = dt;

        string sqlInstore = @"
SELECT cid.containerinstoreid
FROM containerinstore cid
WHERE cid.aufnr = '{0}' AND cid.charg = '{1}' AND cid.isuse = 0";
        sqlInstore = string.Format(sqlInstore, dic["ProductOrderNo"].ToString(), dr["serialCode"].ToString());
        DataTable dtInstore = DatabaseHelper.Query_ReturnDatTable(sqlInstore);

        string containerinstoreid = "";
        if (dtInstore.Rows.Count > 0)
        {
            containerinstoreid = dtInstore.Rows[0]["containerinstoreid"].ToString();
        }

        string json = JsonConvert.SerializeObject(para);
        string insertSql = @"
INSERT INTO sync_sendto_wms(methodname,json,toappid,tablename,uniquecolname,uniquecolvalue,create_emp) 
VALUES('入库申请','{0}','{1}','containerinstore','containerinstoreid','{2}','{3}')";
        insertSql = string.Format(insertSql, json, ToAppID_WMS, containerinstoreid, dic["employeeid"].ToString());
        DatabaseHelper.ExecuteSql(insertSql);
    }
}